package com.gagakuai.bpm.common.interceptor;

import com.gagakuai.bpm.config.redis.TokenRepository;
import com.gagakuai.bpm.domian.dto.camunda.UserInfo;
import com.gagakuai.bpm.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

// import org.camunda.bpm.engine.IdentityService;

@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    private TokenRepository tokenRepository;

//    @Resource
//    private IdentityService identityService;

    /*
     * 根据请求获取token 进行权限难拦截
     * @param request 请求
     * @param response 返回
     * @param handler 转发
     * @return 状态是否
     */
    @Override
    public boolean preHandle(HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable Object handler) {
        String token = request.getParameter("Authorization");
        String _token = request.getHeader("Authorization");

        token = token != null ?  token : _token != null ? _token : UUID.randomUUID().toString();
        if(StringUtils.isBlank(token)) {
            log.info("访问地址需要登录权限：{}", request.getRequestURI());
            assert response != null;
            response.setStatus(401);
            return false;
        }

        UserInfo userInfo =  tokenRepository.get(token);
        if( ObjectUtils.isEmpty(userInfo)){
            log.info("当前用户登陆已失效，请重新登陆！");
            assert response != null;
            response.setStatus(401);
            return false;
        }

        // 根据TOKEN从REDIS获取当前用户信息，然后设置当前操作BPM的操作人ID
        userInfo.setToken(token);
        UserUtil.set(userInfo);
//        identityService.setAuthenticatedUserId(userInfo.getUserId());
        return true;
    }

    @Override
    public  void afterCompletion(@Nullable HttpServletRequest request,@Nullable HttpServletResponse response,@Nullable Object handler,
                                 @Nullable Exception ex) {
       UserUtil.remove();
    }
}
